import EventCenter from "./event_center";
import Event from "./event";
import AssetsLoader from "./assets_loader";

export default class AudioCtrl {
  constructor(e, t?) {
    let n = this;
    if (arguments.length > 0)
      if (typeof e == "string") {
        let r = document.createElement("audio");
        (r.src = e), n.audio(r);
      } else typeof e == "object" && n.audio(e);
    arguments.length > 1 && n.loop(t);
  }
  static audioByURL(e) {
    let t = AssetsLoader.asset(e);
    return new AudioCtrl(t);
  }
  _audio = null;
  audio(e?) {
    let t = this;
    if (typeof e == "object" && t._audio != e) {
      t._audio != null &&
        (t.pause(),
        (t._audio = null),
        t._audio.removeEventListener("playing", t),
        t._audio.removeEventListener("pause", t),
        t._audio.removeEventListener("ended", t)),
        (t._audio = e);
      try {
        t._audio.loop = t.loop();
      } catch (n) {}
      try {
        t._audio.volume = t._volume;
      } catch (n) {}
      t._audio.addEventListener("playing", t),
        t._audio.addEventListener("pause", t),
        t._audio.addEventListener("ended", t);
    }
    return t._audio;
  }
  handleEvent(n) {
    let r = this,
      i = n.type;
    i == "playing"
      ? ((r._playing = !0), EventCenter.dispatchEvent(new Event(r, Event.CHANGE)))
      : i == "pause"
      ? ((r._playing = !1), EventCenter.dispatchEvent(new Event(r, Event.CHANGE)))
      : i == "ended" &&
        (r.loop() ? r.play(0) : EventCenter.dispatchEvent(new Event(r, Event.END)));
  }
  _volume = 1;
  volume(e) {
    let t = this;
    if (isNaN(e) === !1 && t._volume != e) {
      t._volume = e;
      if (t.audio() != null)
        try {
          t.audio().volume = t._volume;
        } catch (n) {}
    }
    return t._volume;
  }
  _playing = !1;
  playing() {
    let e = this;
    return e._playing;
  }
  _loop = !1;
  loop(e?) {
    let t = this;
    if (typeof e == "boolean" && e != t._loop) {
      t._loop = e;
      if (t.audio() != null)
        try {
          t.audio().loop = t._loop;
        } catch (n) {}
    }
    return t._loop;
  }
  play(e) {
    let t = this;
    if (t.audio() != null) {
      if (isNaN(e) === !1)
        try {
          t.audio().currentTime = e;
        } catch (n) {}
      try {
        t.audio().play();
      } catch (n) {}
    }
  }
  pause() {
    let e = this;
    if (e.audio() != null)
      try {
        e.audio().pause();
      } catch (t) {}
  }
  dealloc() {
    let e = this;
    e._audio != null &&
      (e.pause(),
      (e._audio = null),
      e._audio.removeEventListener("playing", e),
      e._audio.removeEventListener("pause", e),
      e._audio.removeEventListener("ended", e),
      (e._audio = null),
      (e._playing = !1),
      (e._loop = !1),
      (e._volume = 1));
  }
}
